from django.shortcuts import render
from django.http import HttpResponse
from django.utils.datastructures import MultiValueDictKeyError
from django.views.decorators.clickjacking import xframe_options_exempt

from myfun.crawler.btbbt import BTBBT
from myfun.crawler.jddm import JDDM


# 全部分类
TABS = [BTBBT(), JDDM()]
# 默认分类
DEF_TAB = TABS[0]
# 模板 搜索
TMP_SEARCH = 'search.html'
# 模板 下载
TMP_DOWNLOAD = 'download.html'


# 结果集
class Result:
    def __init__(self, request):
        request.encoding = 'utf-8'
        self.request = request
        # 返回空
        self.isNone = False
        # 分类
        self.tab = DEF_TAB
        # 主页
        self.main = ''
        # 链接
        self.url = self.getPara('url', '')
        # 单项
        self.one = ''
        # 关键字
        self.kwd = self.getPara('kwd', '')
        # 总页数
        self.ttp = 0
        # 当前页
        self.page = int(self.getPara('page', '1'))
        # 全部分类
        self.tabs = []
        # Item 列表
        self.list = []

        tab = self.getPara('tab', DEF_TAB.tab)
        for item in TABS:
            if tab == item.tab:
                item.this = ' layui-this'
                self.tab = item
            else:
                item.this = ''
            self.tabs.append(item)

    def getPara(self, key, v):
        try:
            v = self.request.GET[key]
        except MultiValueDictKeyError as e:
            pass
        return v

    def getRender(self, tmpl):
        if self.isNone:
            return HttpResponse('none')
        else:
            return render(self.request, tmpl, {
                'tab': self.tab.tab,
                'main': self.main,
                'one': self.one,
                'ttp': self.ttp,
                'kwd': self.kwd,
                'page': self.page,
                'tabs': self.tabs,
                'list': self.list
            })

    def search(self):
        try:
            self.tab.getMovies(self)
        except Exception as e:
            pass
        return self.getRender(TMP_SEARCH)

    def download(self):
        try:
            self.tab.getAttach(self)
        except Exception as e:
            self.isNone = True
        return self.getRender(TMP_DOWNLOAD)


def search(request):
    return Result(request).search()


@xframe_options_exempt
def download(request):
    return Result(request).download()
